#!/bin/sh -e

TOP_DIR=$(pwd)

. CI/travis/lib.sh

get_libiio_release() {
	git clone https://github.com/analogdevicesinc/libiio && cd libiio
	IIO_TAG=`git describe --tags $(git rev-list --tags --max-count=1)`
	git checkout ${IIO_TAG}
	IIO_TAG_SHA=${IIO_TAG}.g`git rev-parse --short HEAD`
	wget https://github.com/analogdevicesinc/libiio/releases/download/${IIO_TAG}/libiio-${IIO_TAG_SHA}${LDIST}.deb
}

handle_centos() {
	# FIXME: see about adding `libserialport-dev` from EPEL ; maybe libusb-1.0.0-devel...
	yum -y groupinstall 'Development Tools'

	if is_centos_at_least_ver "8" ; then
		# On CentOS 8, avahi-devel & doxygen are in this repo; enable it
		yum -y install yum-utils
		yum config-manager --set-enabled powertools
	fi

	yum -y install cmake libxml2-devel libusb1-devel doxygen libaio-devel \
		avahi-devel bzip2 gzip rpm rpm-build swig

	if [ -n "$PACKAGE_TO_INSTALL" ] ; then
		sudo yum localinstall -y $PACKAGE_TO_INSTALL
	elif [ "$INSTALL_FROM_SW_DOWNLOADS" = "1" ] ; then
		wget https://swdownloads.analog.com/cse/azure_builds/${artifactName}_latest_${LIBIIO_BRANCH}_libiio.deb
		sudo dpkg -i ./${artifactName}_latest_${LIBIIO_BRANCH}_libiio.deb
	fi
}

handle_generic_docker() {
	prepare_docker_image
}

handle_default() {
	sudo apt-get -qq update
	sudo DEBIAN_FRONTEND=noninteractive apt-get install -y cmake doxygen graphviz \
		libaio-dev libavahi-client-dev libavahi-common-dev libusb-1.0-0-dev \
		libxml2-dev rpm tar bzip2 gzip flex bison git curl \
		python3-dev python3-setuptools python3-pip python3-all \
		debhelper devscripts fakeroot libserialport-dev swig dh-python

	if [ -n "$PACKAGE_TO_INSTALL" ] ; then
		sudo dpkg -i $PACKAGE_TO_INSTALL
	elif [ "$INSTALL_FROM_SW_DOWNLOADS" = "1" ] ; then
		wget https://swdownloads.analog.com/cse/azure_builds/${artifactName}_latest_${LIBIIO_BRANCH}_libiio.deb
		sudo dpkg -i ./${artifactName}_latest_${LIBIIO_BRANCH}_libiio.deb
	fi

	#Install glog
	cd ${TOP_DIR}
	git clone --branch v0.4.0 --depth 1 https://github.com/google/glog
	mkdir -p glog/build_0_4_0 && cd glog/build_0_4_0
	cmake -DCMAKE_PREFIX_PATH=/usr ..
	make
	sudo make install

	sudo pip3 install --upgrade pip stdeb argparse
}

handle_doxygen() {
	# Install a recent version of doxygen
	DOXYGEN_URL="wget https://sourceforge.net/projects/doxygen/files/rel-1.8.15/doxygen-1.8.15.src.tar.gz"
	cd ${DEPS_DIR}
	[ -d "doxygen" ] || {
		mkdir doxygen && wget --quiet -O - ${DOXYGEN_URL} | tar --strip-components=1 -xz -C doxygen
	}
	cd doxygen
	mkdir -p build && cd build
	cmake ..
	make -j${NUM_JOBS}
	sudo make install
	cd ..
	cd ..

	cd ${TOP_DIR}/doc
	mkdir -p build && cd build
	cmake ..
	cd ..
	cd ..

	handle_default
	cd ${TOP_DIR}
	#Also install Sphinx for Python bindings
	sudo apt-get install python3-sphinx
	sudo pip3 install --upgrade sphinx_rtd_theme
}

handle_ubuntu() {
	handle_default
}

handle_debian() {
	handle_default
}

setup_build_type_env_vars

handle_${BUILD_TYPE}
